using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using S.M.SmartMedical.API.Read.Application.Query;
using S.M.SmartMedical.Domain.DTOs;
using S.M.SmartMedical.Domain.Entities;
using S.M.SmartMedical.ErrorCode;
using S.M.SmartMedical.Infrastructure.BaseRepository;

namespace S.M.SmartMedical.API.Read.Application.Handler
{
    /// <summary>
    /// 获取医院列表查询处理程序
    /// 处理医院分页查询逻辑
    /// </summary>
    public class GetHospitalsHandler : IRequestHandler<GetHospitalsQuery, APIResult<PageResponse<HospitalDto>>>
    {
        private readonly IRepository<Hospital> _hospitalRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetHospitalsHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        public GetHospitalsHandler(
            IRepository<Hospital> hospitalRepository,
            IMapper mapper,
            ILogger<GetHospitalsHandler> logger)
        {
            _hospitalRepository = hospitalRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理医院列表查询请求
        /// </summary>
        public async Task<APIResult<PageResponse<HospitalDto>>> Handle(GetHospitalsQuery request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始查询医院列表，参数：{@Request}", request);

                // 构建查询条件
                var query = _hospitalRepository.GetQueryable();

                // 应用搜索条件
                if (!string.IsNullOrWhiteSpace(request.Name))
                {
                    query = query.Where(h => h.Name.Contains(request.Name));
                }

                if (!string.IsNullOrWhiteSpace(request.Level))
                {
                    query = query.Where(h => h.Level == request.Level);
                }

                if (!string.IsNullOrWhiteSpace(request.Type))
                {
                    query = query.Where(h => h.Type == request.Type);
                }

                // 获取总记录数
                var totalCount = await query.CountAsync(cancellationToken);

                // 获取分页数据
                var hospitals = await query
                    .OrderByDescending(h => h.CreateTime)
                    .Skip((request.CurrentPage - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync(cancellationToken);

                // 映射到DTO
                var hospitalDtos = _mapper.Map<List<HospitalDto>>(hospitals);

                // 构建分页响应
                var result = new PageResponse<HospitalDto>
                {
                    Items = hospitalDtos,
                    TotalCount = totalCount,
                    CurrentPage = request.CurrentPage,
                    PageSize = request.PageSize
                };

                _logger.LogInformation("医院列表查询成功，共找到 {TotalCount} 条记录", totalCount);

                return new APIResult<PageResponse<HospitalDto>>
                {
                    Code = APIEnum.OK,
                    Message = "查询成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询医院列表时发生错误");
                return new APIResult<PageResponse<HospitalDto>>
                {
                    Code = APIEnum.Fail,
                    Message = "查询失败：" + ex.Message
                };
            }
        }
    }
}